package com.maktoub.project.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maktoub.common.model.entity.User;
import com.maktoub.common.model.entity.UserInterfaceInfo;
import com.maktoub.project.annotation.AuthCheck;
import com.maktoub.project.common.BaseResponse;
import com.maktoub.project.common.ErrorCode;
import com.maktoub.project.common.IdRequest;
import com.maktoub.project.common.ResultUtils;
import com.maktoub.project.constant.CommonConstant;
import com.maktoub.project.constant.UserConstant;
import com.maktoub.project.exception.BusinessException;
import com.maktoub.project.model.dto.UserInterfaceInfo.UserInterfaceInfoAddRequest;
import com.maktoub.project.model.dto.UserInterfaceInfo.UserInterfaceInfoQueryRequest;
import com.maktoub.project.model.dto.UserInterfaceInfo.UserInterfaceInfoUpdateRequest;
import com.maktoub.project.model.vo.UserInterfaceInfoExcludedVO;
import com.maktoub.project.model.vo.UserInterfaceInfoVO;
import com.maktoub.project.service.UserInterfaceInfoService;
import com.maktoub.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/userInterfaceInfo")
@Slf4j
public class UserInterfaceInfoController {

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;
    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param userInterfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck( mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUserInterfaceInfo(@RequestBody UserInterfaceInfoAddRequest userInterfaceInfoAddRequest, HttpServletRequest request) {
        if (userInterfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceInfoAddRequest, userInterfaceInfo);
        
        // 校验,添加，与其他校验传入得参数就是一个add不一样
        userInterfaceInfoService.validUserInterfaceInfo(userInterfaceInfo, true);

        //leftNum和totalNum为默认0
        boolean result = userInterfaceInfoService.save(userInterfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newUserInterfaceInfoId = userInterfaceInfo.getId();
        return ResultUtils.success(newUserInterfaceInfoId);//返回用户接口记录id信息
    }

    /**
     * 删除
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck( mustRole = UserConstant.ADMIN_ROLE)
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteUserInterfaceInfo(@RequestBody List<IdRequest> idRequest, HttpServletRequest request) {

        if (idRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        int i = 0;
        for (IdRequest item : idRequest) {
            long id = item.getId();
            // 判断是否存在
            UserInterfaceInfo oldUserInterfaceInfo = userInterfaceInfoService.getById(id);
            if (oldUserInterfaceInfo == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            // 仅本人或管理员可删除
            if (!oldUserInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            boolean b = userInterfaceInfoService.removeById(id);
        }

        return ResultUtils.success(true);
    }

    /**
     * 更新
     *
     * @param userInterfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck( mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserInterfaceInfo(@RequestBody UserInterfaceInfoUpdateRequest userInterfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (userInterfaceInfoUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceInfoUpdateRequest, userInterfaceInfo);
        // 参数校验
        userInterfaceInfoService.validUserInterfaceInfo(userInterfaceInfo, false);



        long id = userInterfaceInfoUpdateRequest.getId();
        // 判断是否存在
        UserInterfaceInfo oldUserInterfaceInfo = userInterfaceInfoService.getById(id);
        if (oldUserInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 仅本人或管理员可修改
        User user = userService.getLoginUser(request);
        if (!(oldUserInterfaceInfo.getUserId().equals(user.getId())) && !(userService.isAdmin(request))) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // todo 测试类中字段为空，update会更新成什么，还是不更新
        userInterfaceInfo.setUpdateTime(DateTime.now());
        boolean result = userInterfaceInfoService.updateById(userInterfaceInfo);
        return ResultUtils.success(result);
    }



    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserInterfaceInfo> getUserInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getById(id);
        return ResultUtils.success(userInterfaceInfo);
    }

    @GetMapping("/user_interface/userId")
    public BaseResponse<List<UserInterfaceInfoVO> > getUserInterfaceInfoByUserId(
            UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        long userId = loginUser.getId();
        userInterfaceInfoQueryRequest.setUserId(userId);
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        System.out.println("userInterfaceInfoQueryRequest = " + userInterfaceInfoQueryRequest);
        List<UserInterfaceInfoVO>  userInterfaceInfoVO = userInterfaceInfoService.getByUserId(userInterfaceInfoQueryRequest);
        return ResultUtils.success(userInterfaceInfoVO);
    }


    /**
     * 获取列表（仅管理员可使用）
     *
     * @param userInterfaceInfoQueryRequest
     * @return
     */
    @AuthCheck( mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/list")
    public BaseResponse<List<UserInterfaceInfo>> listUserInterfaceInfo(
            UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest) {
        UserInterfaceInfo userInterfaceInfoQuery = new UserInterfaceInfo();
        if (userInterfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(userInterfaceInfoQueryRequest, userInterfaceInfoQuery);
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>(userInterfaceInfoQuery);
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoService.list(queryWrapper);
        return ResultUtils.success(userInterfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param userInterfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<UserInterfaceInfo>> listUserInterfaceInfoByPage(UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest, HttpServletRequest request) {
        if (userInterfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        long current = userInterfaceInfoQueryRequest.getCurrent();
        long size = userInterfaceInfoQueryRequest.getPageSize();
        String sortField = userInterfaceInfoQueryRequest.getSortField();
        String sortOrder = userInterfaceInfoQueryRequest.getSortOrder();
        

        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        QueryWrapper<UserInterfaceInfo> userInterfaceInfoQueryRequestQueryWrapper =
                new QueryWrapper<UserInterfaceInfo>()
                .orderBy(StringUtils.isNotBlank(sortField),
                        sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                        sortField);

        Page<UserInterfaceInfo> userInterfaceInfoPage =
                userInterfaceInfoService.page(new Page<>(current, size),
                        userInterfaceInfoQueryRequestQueryWrapper);

        return ResultUtils.success(userInterfaceInfoPage);
    }

    @GetMapping("/list/page/excludeUserId")
    public BaseResponse<Page<UserInterfaceInfoExcludedVO>> listInterfaceInfoNotOwnByPage(UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest,
                                                                                         HttpServletRequest request) {
        Page<UserInterfaceInfoExcludedVO> byExcluedUserId = userInterfaceInfoService.getByExcluedUserId(userInterfaceInfoQueryRequest, request);
        return ResultUtils.success(byExcluedUserId);
    }
}
